package cn.gp.chatclient.ui.panel;

import cn.gp.chatclient.api.user.req.UpdateProfileRequest;
import cn.gp.chatclient.model.UserVo;
import cn.gp.chatclient.service.UserService;
import cn.gp.chatclient.utils.ImageUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.net.URL;

/**
 * @ClassName ProfilePanel
 * @Description TODO
 * @Author He Guoping
 * @Date 2025/6/17 9:16
 * @Version JDK17
 */
@Slf4j
public class ProfilePanel extends JPanel {
    private final UserVo currentUser;
    private final UserService userService;
    private JLabel avatarLabel;
    private JLabel nicknameLabel;
    private JLabel usernameLabel;

    public ProfilePanel(UserVo currentUser) {
        this.currentUser = currentUser;
        this.userService = new UserService();
        setLayout(new BorderLayout());
        setBackground(Color.WHITE);

        // 创建主面板
        JPanel mainPanel = new JPanel();
        mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
        mainPanel.setBackground(Color.WHITE);
        mainPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        // 添加标题
        JLabel titleLabel = new JLabel("个人信息", SwingConstants.CENTER);
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 20));
        titleLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
        mainPanel.add(titleLabel);
        mainPanel.add(Box.createVerticalStrut(20));

        // 创建头像面板
        JPanel avatarPanel = new JPanel();
        avatarPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
        avatarPanel.setBackground(Color.WHITE);
        avatarLabel = new JLabel();
        avatarLabel.setPreferredSize(new Dimension(100, 100));
        avatarPanel.add(avatarLabel);
        mainPanel.add(avatarPanel);
        mainPanel.add(Box.createVerticalStrut(20));

        // 创建昵称面板
        JPanel nicknamePanel = new JPanel();
        nicknamePanel.setLayout(new FlowLayout(FlowLayout.CENTER));
        nicknamePanel.setBackground(Color.WHITE);
        nicknameLabel = new JLabel();
        nicknameLabel.setFont(new Font("微软雅黑", Font.BOLD, 18));
        nicknamePanel.add(nicknameLabel);
        mainPanel.add(nicknamePanel);
        mainPanel.add(Box.createVerticalStrut(10));

        // 创建用户名面板
        JPanel usernamePanel = new JPanel();
        usernamePanel.setLayout(new FlowLayout(FlowLayout.CENTER));
        usernamePanel.setBackground(Color.WHITE);
        usernameLabel = new JLabel();
        usernameLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        usernameLabel.setForeground(new Color(128, 128, 128));
        usernamePanel.add(usernameLabel);
        mainPanel.add(usernamePanel);

        // 添加"修改个人信息"按钮
        JButton editButton = new JButton("修改个人信息");
        editButton.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        editButton.setFocusPainted(false);
        editButton.addActionListener(e -> {
            if (currentUser == null || currentUser.getId() == null) {
                JOptionPane.showMessageDialog(this, 
                    "请先登录后再修改个人信息", 
                    "提示", 
                    JOptionPane.WARNING_MESSAGE);
                return;
            }
            openEditProfileDialog();
        });
        JPanel btnPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        btnPanel.setBackground(Color.WHITE);
        btnPanel.add(editButton);
        mainPanel.add(Box.createVerticalStrut(20));
        mainPanel.add(btnPanel);

        // 添加主面板到中心
        add(mainPanel, BorderLayout.CENTER);

        // 加载初始用户信息
        loadUserInfo();
    }

    private void loadUserInfo() {
        // 设置昵称
        nicknameLabel.setText(currentUser.getNickname());

        // 设置用户名
        usernameLabel.setText("@" + currentUser.getUsername());

        // 加载头像
        if (StrUtil.isNotBlank(currentUser.getAvatar())) {
            try {
                ImageIcon avatarIcon = ImageUtil.getAvatarIcon(currentUser.getAvatar(), 100, 100);
                avatarLabel.setIcon(avatarIcon);
            } catch (Exception e) {
                // 如果加载失败，使用默认头像
                avatarLabel.setIcon(createDefaultAvatar(currentUser.getNickname()));
            }
        } else {
            // 如果没有头像，使用默认头像
            avatarLabel.setIcon(createDefaultAvatar(currentUser.getNickname()));
        }
    }

    private void openEditProfileDialog() {
        JTextField nicknameField = new JTextField(currentUser.getNickname(), 15);
        JTextField avatarField = new JTextField(currentUser.getAvatar() == null ? "" : currentUser.getAvatar(), 15);
        JPanel panel = new JPanel(new GridLayout(0, 1, 5, 5));
        panel.add(new JLabel("昵称:"));
        panel.add(nicknameField);
        panel.add(new JLabel("头像URL:"));
        panel.add(avatarField);
        int result = JOptionPane.showConfirmDialog(this, panel, "修改个人信息", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
        if (result == JOptionPane.OK_OPTION) {
            String newNickname = nicknameField.getText().trim();
            String newAvatar = avatarField.getText().trim();
            if (!newNickname.isEmpty()) {
                // 创建更新请求
                UpdateProfileRequest request = new UpdateProfileRequest();
                request.setId(currentUser.getId());
                request.setNickname(newNickname);
                request.setAvatar(newAvatar.isEmpty() ? null : newAvatar);

                // 调用服务更新个人信息
                userService.updateProfile(request).thenAccept(responseVo -> {
                    if (responseVo.isSuccess()) {
                        // 更新成功，刷新显示
                        SwingUtilities.invokeLater(() -> {
                            UserVo updatedUser = responseVo.getData();
                            currentUser.setNickname(updatedUser.getNickname());
                            currentUser.setAvatar(updatedUser.getAvatar());
                            currentUser.setStatus(updatedUser.getStatus());
                            loadUserInfo();
                            JOptionPane.showMessageDialog(this, "个人信息更新成功！");
                        });
                    } else {
                        // 更新失败，显示错误信息
                        SwingUtilities.invokeLater(() -> {
                            JOptionPane.showMessageDialog(this, "更新失败：" + responseVo.getMessage(), 
                                "错误", JOptionPane.ERROR_MESSAGE);
                        });
                    }
                }).exceptionally(throwable -> {
                    // 发生异常，显示错误信息
                    SwingUtilities.invokeLater(() -> {
                        JOptionPane.showMessageDialog(this, "更新失败：" + throwable.getMessage(), 
                            "错误", JOptionPane.ERROR_MESSAGE);
                    });
                    return null;
                });
            }
        }
    }

    private ImageIcon createDefaultAvatar(String nickname) {
        // 创建默认头像
        BufferedImage image = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = image.createGraphics();

        // 设置抗锯齿
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        // 绘制圆形背景
        g2d.setColor(new Color(70, 130, 180));
        g2d.fillOval(0, 0, 100, 100);

        // 绘制文字
        g2d.setColor(Color.WHITE);
        g2d.setFont(new Font("微软雅黑", Font.BOLD, 40));
        String initial = nickname.substring(0, 1).toUpperCase();
        FontMetrics fm = g2d.getFontMetrics();
        int x = (100 - fm.stringWidth(initial)) / 2;
        int y = ((100 - fm.getHeight()) / 2) + fm.getAscent();
        g2d.drawString(initial, x, y);

        g2d.dispose();
        return new ImageIcon(image);
    }

    public void refreshProfile() {
        // 暂时禁用自动刷新，只显示初始数据
        log.info("个人信息面板刷新已禁用");
    }
}
